<template>
  <div>
    <!-- 评论列表 -->
    <van-list
      class="cmt-list"
      v-model="loading"
      :finished="finished"
      finished-text="没有更多评论了"
      :immediate-check="false"
      @load="onLoad"
    >
      <!-- 评论的 Item 项 -->
      <div class="cmt-item" v-for="item in cmtList" :key="item.pubdate">
        <!-- 头部区域 -->
        <div class="cmt-header">
          <!-- 头部左侧 -->
          <div class="cmt-header-left">
            <img :src="item.aut_photo" alt="" class="avatar" />
            <span class="uname">{{ item.aut_name }}</span>
          </div>
          <!-- 头部右侧 -->
          <div class="cmt-header-right">
            <van-icon
              v-if="item.is_liking"
              name="like"
              size="16"
              color="red"
              @click="delLikeCmt(item)"
            />
            <van-icon
              v-else
              name="like-o"
              size="16"
              color="gray"
              @click="addLikeCmt(item)"
            />
          </div>
        </div>
        <!-- 主体区域 -->
        <div class="cmt-body">
          <!-- 基于字体的图标集，可以通过 Icon 组件使用，也可以在其他组件中通过 icon
          属性引用。基于字体的图标集，可以通过 Icon
          组件使用，也可以在其他组件中通过 icon 属性引用。 -->
          {{ item.content }}
        </div>
        <!-- 尾部区域 -->
        <div class="cmt-footer">{{ item.pubdate }}</div>
      </div>
    </van-list>
    <!-- 底部添加评论区域 - 1 -->
    <div v-if="isShowBox1" class="add-cmt-box van-hairline--top">
      <van-icon name="arrow-left" size="18" @click="$router.back()" />
      <div class="ipt-cmt-div" @click="showBox2">发表评论</div>
      <div class="icon-box">
        <van-badge :content="cmtCount" :max="99">
          <van-icon name="comment-o" size="20" @click="scrollToCmtList" />
        </van-badge>
        <van-icon name="star-o" size="20" />
        <van-icon name="share-o" size="20" />
      </div>
    </div>

    <!-- 底部添加评论区域 - 2 -->
    <div v-else class="cmt-box van-hairline--top">
      <textarea
        placeholder="友善评论、理性发言、阳光心灵"
        ref="iptCmt"
        v-model.trim="cmt"
        @blur="hideBox2"
      ></textarea>
      <van-button type="default" :disabled="cmt.length === 0" @click="pubCmt">
        发布
      </van-button>
    </div>
  </div>
</template>

<script>
import {
  getCmtList,
  addLikeCmt,
  delLikeCmt,
  pubComment,
} from '@/api/request.js'
import { animate } from 'popmotion'
export default {
  name: 'ArtCmt',
  props: {
    // 文章的id
    artId: {
      type: [String, Number],
      // required: true,
    },
  },
  data() {
    return {
      // 评论数据
      cmtList: [],
      // 偏移量
      offset: null,
      // 是否正在请求上拉加载的数据
      loading: true,
      // 所有数据是否都加载完毕了
      finished: false,
      // 控制展示底部按钮或者输入框
      isShowBox1: true,
      // 当前文章的总评论数
      cmtCount: 0,
      // 用户填写的评论内容
      cmt: '',
    }
  },
  created() {
    this.getCmtList()
  },
  methods: {
    // 获取评论列表数据
    async getCmtList() {
      const params = {
        type: 'a',
        source: this.artId,
        offset: this.offset,
      }

      const { data: res } = await getCmtList(params)
      // console.log(res);
      const { message, data } = res
      if (message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取评论数据失败' })
      }
      // 为总评论数赋值
      this.cmtCount = data.total_count
      this.offset = data.last_id
      this.cmtList = [...this.cmtList, ...data.results]
      this.loading = false
      if (data.results.length === 0) {
        this.finished = true
      }
    },
    // 评论下拉加载
    onLoad() {
      this.getCmtList()
    },
    // 点赞评论
    async addLikeCmt(item) {
      const data = {
        target: item.com_id,
      }
      const { data: res } = await addLikeCmt(data)
      // console.log(res);
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '点赞失败请稍后重试' })
      }
      item.is_liking = true
      this.$notify({ type: 'success', message: '点赞成功' })
    },
    // 取消点赞评论
    async delLikeCmt(item) {
      const res = await delLikeCmt(item.com_id)
      // console.log(res);
      if (res.status !== 204) {
        return this.$notify({ type: 'danger', message: '取消点赞失败' })
      }
      item.is_liking = false
      this.$notify({ type: 'success', message: '取消成功' })
    },
    // 点击发表评论
    showBox2() {
      this.isShowBox1 = false
      this.$nextTick(() => {
        this.$refs.iptCmt.focus()
      })
    },
    // 输入框的失焦事件
    hideBox2() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.isShowBox1 = true
        // 清空用户输入的评论内容
        this.cmt = ''
      }, 100)
    },
    // 点击发布
    async pubCmt() {
      // console.log(this.cmt);
      const data = {
        target: this.artId,
        content: this.cmt,
      }
      const { data: res } = await pubComment(data)
      // console.log(res);
      if (res.message !== 'OK') {
        return this.$notify({ type: 'denger', message: '评论失败请稍后重试' })
      }
      this.cmtCount += 1
      // 动态给响应回来的数据添加 is_liking 属性
      res.data.new_obj.is_liking = false
      this.cmtList.unshift(res.data.new_obj)
      this.$notify({ type: 'success', message: '评论成功' })
    },
    // 点击评论图标滑动到评论列表
    scrollToCmtList() {
      // 1. 当前滚动条的位置
      const now = window.scrollY
      // 2. 目标位置（文章信息区域的高度）
      const dist = document.querySelector('.article-container').offsetHeight

      // 3. 实现滚动动画
      animate({
        from: now, // 当前的位置
        to: dist, // 目标位置
        onUpdate: (latest) => window.scrollTo(0, latest),
      })
    },
  },
}
</script>

<style lang="less" scoped>
.cmt-list {
  padding: 10px;
  .cmt-item {
    padding: 15px 0;
    + .cmt-item {
      border-top: 1px solid #f8f8f8;
    }
    .cmt-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .cmt-header-left {
        display: flex;
        align-items: center;
        .avatar {
          width: 40px;
          height: 40px;
          background-color: #f8f8f8;
          border-radius: 50%;
          margin-right: 15px;
        }
        .uname {
          font-size: 12px;
        }
      }
    }
    .cmt-body {
      font-size: 14px;
      line-height: 28px;
      text-indent: 2em;
      margin-top: 6px;
      word-break: break-all;
    }
    .cmt-footer {
      font-size: 12px;
      color: gray;
      margin-top: 10px;
    }
  }
}
</style>
<style lang="less" scoped>
// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    margin-left: 10px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}
</style>
